import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
//element plus 按需引入
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'


// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  // const BASE_URL = env.VITE_APP_WEB_BASE_URL

  // const BASE_TARGET = env.VITE_APP_WEB_BASE_TARGET
  return {
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        //配置element plus 采用sass样式配色系统
        resolvers: [ElementPlusResolver({ importStyle: "sass" })],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 自动导入定制化样式文件进行样式覆盖
          additionalData: `
            @use "@/styles/element/index.scss" as *;
            @use "@/styles/var.scss" as *;
          `,
        }
      }
    },
    base: '/',
    server: {
      //本地服务器主机名 配置后可以使用本地网络访问
      host: '0.0.0.0',
      //指定启动端口号
      port: 5173,
      //设为 true 时若端口已被占用则会直接退出，而不是尝试下一个可用端口
      strictPort: false,
      //服务器启动时自动在浏览器中打开应用程序,当此值为字符串时，会被用作 URL 的路径名
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_WEB_BASE_TARGET, // test
          changeOrigin: true,
          secure: false, // 添加这一行以禁用 SSL 证书验证
          rewrite: (path) => path.replace(new RegExp('/api', ''), ''),
        },
        '/msg_pay': {
          target: env.VITE_APP_WEB_BASE_TARGET_MSG_PAY,
          changeOrigin: true,
          secure: false, // 添加这一行以禁用 SSL 证书验证
          rewrite: (path) => path.replace(new RegExp('/msg_pay', ''), ''),
        },
        '/admin': {
          target: env.VITE_APP_WEB_BASE_TARGET_ADMIN,
          changeOrigin: true,
          secure: false, // 添加这一行以禁用 SSL 证书验证
          rewrite: (path) => path.replace(new RegExp('/admin', ''), ''),
        },
        '/recom': {
          target: env.VITE_APP_WEB_BASE_TARGET_RECOM,
          changeOrigin: true,
          secure: false, // 添加这一行以禁用 SSL 证书验证
          rewrite: (path) => path.replace(new RegExp('/recom', ''), ''),
        },
        '/order': {
          target: env.VITE_APP_WEB_BASE_TARGET_ORDER,
          changeOrigin: true,
          secure: false, // 添加这一行以禁用 SSL 证书验证
          // rewrite: (path) => path.replace(new RegExp('/order', ''), ''),
        }
      }
    },
  }
})
